<template>
    <nly-content-wrapper class="content-warpper-2" :style="addBtnShow?{'border':'none'}:{}">
        <div class="content-header-2">
            <!--按钮-->
            <div class="btn-wrapper clearfix" :style="addBtnShow?{'border':'none','padding-top':'0','height':'52px' }:{}">
                <a-row class="text-center clearfix">
                    <a-col v-if="addBtnShow" style="text-align:left;line-height:52px;">
                        <a-button :disabled="isHistoryFlag" @click="AddItem" class="margin-left-10 margin-right-10" type="primary" ghost>
                            <a-icon type="file-add" theme="filled" />新增
                        </a-button>
                        <a-button :disabled="isHistoryFlag" @click="EditItem()" class="margin-right-10" type="primary" ghost>
                            <a-icon type="edit" theme="filled" />编辑
                        </a-button>
                        <a-button :disabled="isHistoryFlag" @click="Disable" class="margin-right-10" type="primary" ghost>
                            <a-icon type="delete" theme="filled" />删除
                        </a-button>
                        <a-button :disabled="isHistoryFlag" @click="setKP" class="margin-right-10" type="primary" ghost>
                            <a-icon type="edit" theme="filled" />设置KP
                        </a-button>
                        <a-button :disabled="isHistoryFlag" v-if="addTaskBtnShow" @click="onTaskShow" class="margin-right-10" type="primary" ghost>
                            <a-icon type="file-add" theme="filled" />加入外呼任务
                        </a-button>
                        <a-button v-if="!isHistoryFlag" @click="PageList('history')" class="margin-right-10" type="primary" ghost>
                            <a-icon type="clock-circle" theme="filled" />变更列表
                        </a-button>
                        <a-button v-else @click="PageList()" class="margin-right-10" type="primary" ghost>
                            <a-icon type="clock-circle" theme="filled" />查看列表
                        </a-button>
                        <!-- <a-button @click="onShowSerch" class="margin-right-10">
                            <a-icon type="file-search" />查询
                        </a-button> -->
                        <!-- <a-button @click="showMySet" class="margin-right-10">
                            <a-icon type="setting" />自定义列
                        </a-button> -->
                    </a-col>
                    <a-col v-else :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="AddItem">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="editBtnShow">
                            <div class="btns" @click="EditItem()">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">编辑</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="disableBtnShow">
                            <div style="position:relative">
                                <div class="btns" @click="Disable">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                                <div style="position:absolute;width:2px;height:36px;border-radius:6px;background:#ccc;top:0px;right:0px;"></div>
                            </div>
                        </a-col>

                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="showMySet">
                                <a-icon class="btns-icon" type="setting" />
                                <div class="btns-text">自定义列</div>
                            </div>
                        </a-col>
                        <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                            <div class="btns" @click="GetCustomizeList">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">同步设置</div>
                            </div>
                        </a-col>
                    </a-col>

                </a-row>
            </div>
            <!-- 查询方案 -->
            <a-col :span="24" v-if="!addBtnShow">
                <div class="search-btn-box-gw">
                    <div class="item-small" ref="planLi">
                        <ul>
                            <li class="item-plan" :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                            <li class="item-plan" :title="item.searchName" :class="item.id == planActive?'active':''" v-for="(item,index) in userSearchList" :key="index" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                            <li class="item-plan" @click="onShowSerch">
                                <!-- <a-icon class="icon-searh-btn" type="file-search" /> 查询 -->
                                自定查询
                                <a-icon class="icon-searh-btn" type="search" />
                            </li>
                        </ul>
                    </div>
                    <div class="item-small-down" v-if="showDownPlan" @click="showDownPlanFun">
                        <a-icon v-if="iconDirection" type="down" />
                        <a-icon v-else type="up" />
                    </div>
                </div>
            </a-col>
            <!-- 查询方案结束 -->

            <!-- <nly-row class="col-12">
                <nly-row class="col-12">
                    <fixed-condition :conditions="conditions" :FixedConditionKeys="FixedConditionKeys" :show="show" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></fixed-condition>
                    <div class="mb-1">
                        <nly-button @click="showFunction" variant="info" button-class="mr-2"><i :class="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />{{ show ? "折 叠" : "展 开" }}
                        </nly-button>
                        <nly-button variant="info" @click="onSerch" button-class="mr-2" :disabled="loading">查询</nly-button>
                        <nly-button variant="info" button-class="mr-2" @click="reset" :disabled="loading">重置</nly-button>

                        <nly-button variant="info" @click="showUsModal" button-class="mr-2">保存常用查询</nly-button>

                    </div>
                </nly-row>
            </nly-row>
            <dynamic-condition :conditions="conditions" :FixedConditionKeys="FixedConditionKeys" :show="show" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition> -->

            <a-drawer class="mySet" title="自定义列" width="520" height="300" :maskClosable="true" :visible="mySetVisible">
                <a-checkbox-group v-model="mySetcheckedListLocal" :options="mySetplainOptions" @change="onMySetChange" />
                <nly-col xs="12" sm="12" class="form-inline align-self-start mt-3" style>
                    <nly-button-group>
                        <nly-button variant="danger" @click="onMySetClose" button-class="mr-2">关闭</nly-button>
                        <nly-button variant="info" button-class="mr-2" @click="saveMyShow">确定</nly-button>
                    </nly-button-group>
                </nly-col>
            </a-drawer>
            <nly-container fluid></nly-container>
        </div>
        <!-- 功能操作 -->
        <!-- <div>
            <a-button type="primary" class="crm-btn" @click="EditItem()" v-if="editBtnShow">编辑</a-button>
            <a-button type="primary" class="crm-btn" @click="Disable" v-if="disableBtnShow">删除</a-button>
            <a-button type="primary" class="crm-btn" @click="AddItem" v-if="addBtnShow">新增</a-button>
            <i class="fa fa-fw fa-cog fieldSet " @click="showMySet"></i>
        </div> -->
        <nly-content>
            <!-- 列表 -->
            <a-table id="linkMan_tb" :columns="columns" :rowClassName="rowClassName" :data-source="data" :scroll="{ x: 500, y: 500 }" bordered :loading="loading" :pagination="pagination" @change="onTableChange" :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}">
                <a slot="crmName" slot-scope="text, record" @click="goToDetail(record,'linkMan')" class="goToDetail">
                    {{record.crmName}}
                </a>
                <!-- <a slot="crmName" slot-scope="text, record" @click="EditItem(record.id)" class="goToDetail">
                    {{record.crmName}}
                </a> -->
                <a slot="name" slot-scope="text, record" @click="EditItem(record.id)" class="goToDetail">
                    {{text}}
                </a>
                <div slot="isMain" slot-scope="text">
                    {{text ? "是":"否"}}
                </div>
                <div slot="mobile" slot-scope="text,record">
                    {{text}}
                </div>
                 <div slot="callingOpration" class="phone-class" slot-scope="text,record">
                    <a-icon v-show="record.mobile"  @click="OpenCallingBox(record)"  type="phone" theme="twoTone" two-tone-color="#52c41a"/>
                </div>
                
            </a-table>
            <!-- modal 弹窗  -->
            <drag-modal :visible="ModalVisible" :title="formPostData.id ? '编辑联系人' : '新增联系人'" @cancel="hideModal" class="add-or-edit-modal" style="overflow:hidden">
                <div style="width:560px;overflow:hidden">
                    <nly-row class="form-inline" v-if="!addBtnShow" style="width:828px;">
                        <nly-col xs="6" sm="6" lg="6">
                            <form-select title="客户名称" labelStyle="" rightClass="myRightClass" class="ml-1 mb-2" :required="true" :error="errors['formPostData.crmId']" :showSearch="true" :dataList="customerSelect" :handleSearch="delaySearch" :filterOption="false" v-model="formPostData.crmId" @input="inputLog" :valueTitle.sync="formPostData.crmName" :disabled="customerId">
                            </form-select>
                        </nly-col>
                    </nly-row>
                </div>

                <div class="min-box">
                    <!-- 动态 表单  -->
                    <dynamic-form :formPostData="formPostData" :initFormData="initFormData" :errors="formErrors" :isOk="isFromShow"></dynamic-form>

                    <a-divider v-if="formPostData.id" orientation="left" style="margin:0px 0px 1rem 0px;">其他信息</a-divider>
                    <a-row v-if="formPostData.id" class="form-inline row-cols-12 other-info not-border-form">
                        <a-col :span="24">
                            <form-input title="创建人" labelStyle="" rightClass="myRightClass" :value="formPostData.createUserName" :readonly="true"></form-input>
                        </a-col>
                        <a-col :span="24">
                            <form-input title="创建时间" labelStyle="" rightClass="myRightClass" :value="formPostData.createDate" :readonly="true"></form-input>
                        </a-col>
                        <a-col :span="24">
                            <form-input title="修改人" labelStyle="" rightClass="myRightClass" :value="formPostData.updateUserName" :readonly="true"></form-input>
                        </a-col>
                        <a-col :span="24">
                            <form-input title="修改时间" labelStyle="" rightClass="myRightClass" :value="formPostData.updateDate" :readonly="true"></form-input>
                        </a-col>
                    </a-row>
                </div>
                <template slot="footer">
                    <div>
                        <a-button type="primary" @click="onSubmit">确认</a-button>
                        <a-button @click="hideModal" class="margin-left-10">关闭</a-button>
                    </div>
                </template>
            </drag-modal>
            <!-- 常用查询名称编辑框 -->
            <a-modal title="保存常用查询" :visible="UsVisible" @ok="UserSearchSave" @cancel="hideUsModal">
                <nly-row class="form-inline">
                    <form-input title="名称" rightStyle="flex-grow:1;" class="ml-1 mb-1" style="flex:0.8;" :error="myUsErrors['userSearchEditItem.searchName']" :required="true" v-model="userSearchEditItem.searchName"></form-input>
                </nly-row>
            </a-modal>

            <!-- 查询方案弹窗 -->
            <a-modal class="search-wrapper-box-crm" :visible="visibleSearchPlan" title="查询" @cancel="cancel" width="1000px">
                <div class="content-box">
                    <div class="left-box">
                        <a-row class="btn-wrapper">
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?UserSearchSave():''">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">保存</div>
                                </div>
                            </a-col>
                            <a-col :span="6">
                                <div class="btns" @click="showUsModal(2)">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">另存</div>
                                </div>
                            </a-col>
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?showUsModal(1):''">
                                    <a-icon class="btns-icon" type="edit" />
                                    <div class="btns-text">修改</div>
                                </div>
                            </a-col>
                            <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                <div class="btns" @click="planActive != 0?onUserSearchDelete({key:planActive}):''">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                            </a-col>
                        </a-row>
                        <div class="plan-list">
                            <ul>
                                <li :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                                <li v-for="(item,index) in userSearchList" :key="index" :class="item.id == planActive?'active':''" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                            </ul>
                        </div>
                    </div>
                    <div class="right-box">
                        <a-tabs default-activeKey="1" @change="callback">
                            <a-tab-pane key="1" tab="查询条件">
                                <dynamic-condition v-if="visibleSearchPlan" :checkable="true" :conditions="conditions" :show="true" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition>
                            </a-tab-pane>
                        </a-tabs>
                    </div>
                </div>
                <template slot="footer">
                    <div>
                        <!-- <div style="float:left">
                            <a-checkbox :checked="planActive == defaultPlanActive?true:false" @change="inPagePlanSave">
                                下次以此方案进入
                            </a-checkbox>
                        </div> -->
                        <a-button type="primary" @click="onSerch">查询</a-button>
                        <a-button @click="cancel" class="margin-left-10">取消</a-button>
                    </div>
                </template>
                <a-modal :title="nowPlanType==1?'保存为另一个方案':'修改方案标题'" :visible="saveASVisible" width="400px" centered @cancel="saveAsPlanClose">
                    <a-input v-model="saveAsName" placeholder="请输入查询方案名称"></a-input>
                    <template slot="footer">
                        <div>
                            <a-button type="primary" @click="saveAsPlanSubmit(1)">确定</a-button>
                            <a-button @click="saveAsPlanClose" class="margin-left-10">取消</a-button>
                        </div>
                    </template>
                </a-modal>
            </a-modal>
            <!-- <div class="call-wrapper" :class="callOpen?'call-wrapper-show':'call-wrapper-close'">
                <div class="call-title">呼叫中心消息通知</div>
                <div class="call-content">
                    <i class="fa fa-fw fa-phone fa-text"></i>
                    <div class="call-status">{{talkState}}</div>
                    <a-button class="call-close" @click="OnHangup" type="danger">挂断</a-button>
                </div>

            </div> -->
            <!-- 外呼列表任务弹窗 -->
            <drag-modal  :visible="taskModalVisible" @cancel="onTaskClose" width="1000px" >
                <template slot="title">
                    <div>
                        {{isAddTask ? '该客户已经添加到指定任务' : '可以加入的外呼任务'}}
                    </div>
                </template>
                <div>
                    <div style="display:flex;justify-content: end;">
                        <a-button v-show="!isAddTask" type="primary" style="width: 90px;margin-right:18px;"   @click="addTask">
                            新建任务
                        </a-button>
                         <!-- <a-icon v-show="!isAddTask" type="file-add" @click="addTask" :style="{ fontSize: '28px', color: '#08c' ,cursor: 'pointer',marginLeft:'20px',lineHeight:'24px'}"/> -->
                    </div>
                    <div class="form-search-wrapper" style="min-height:200px;">
                        <a-table :scroll="{ x: auto, y: 400}" :columns="taskColumns" :data-source="taskData"  bordered :pagination="taskPagination" :customRow="taskCustomClick" :loading="taskIsLoadingSearching">
                            <div slot="taskNameFilterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                               <a-input  :placeholder="`搜索${column.title}`" v-model="taskPostData[column.dataIndex]" @pressEnter="() => {taskPostData.page.current = 1;taskPage();}" @ style="width: 188px; margin-bottom: 8px; display: block;"  />
                                <a-button size="small" style="width: 90px;margin-right:8px;" @click="() => {taskPostData[column.dataIndex]='';taskPage();}">
                                    重置
                                </a-button>
                                <a-button type="primary" icon="search" size="small" style="width: 90px;" @click="() => {taskPostData.page.current = 1;taskPage();}">
                                    搜索
                                </a-button>
                            </div>
                            <div slot="callTypeFilterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                                <a-radio-group v-model="taskPostData[column.dataIndex]" @change="() => {taskPostData.page.current = 1;taskPage();}" style="flex-direction: column;">
                                    <a-radio :style="radioStyle" :value="null">
                                    所有
                                    </a-radio>
                                    <a-radio :style="radioStyle" :value="1">
                                    人工
                                    </a-radio>
                                    <a-radio :style="radioStyle" :value="2">
                                    去电放音
                                    </a-radio>
                                </a-radio-group>
                            </div>
                            <!-- 销售联系", "客户关怀","售后回访","投诉回访","服务支持","维修维护","客户投诉" -->
                            <div slot="taskTypeFilterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                                <a-radio-group v-model="taskPostData[column.dataIndex]" @change="() => {taskPostData.page.current = 1;taskPage();}" style="flex-direction: column;">
                                    <a-radio :style="radioStyle" :value="null">
                                    所有
                                    </a-radio>
                                    <a-radio :style="radioStyle" :value="1">
                                    销售联系
                                    </a-radio>
                                    <a-radio :style="radioStyle" :value="2">
                                    客户关怀
                                    </a-radio>
                                    <a-radio :style="radioStyle" :value="3">
                                    售后回访
                                    </a-radio>
                                      <a-radio :style="radioStyle" :value="4">
                                    投诉回访
                                    </a-radio>
                                    <a-radio :style="radioStyle" :value="5">
                                    服务支持
                                    </a-radio>
                                    <a-radio :style="radioStyle" :value="6">
                                    维修维护
                                    </a-radio>
                                    <a-radio :style="radioStyle" :value="7">
                                    客户投诉
                                    </a-radio>
                                </a-radio-group>
                            </div>
                        
                        
                        </a-table>
                    </div>
                </div>
            </drag-modal>
            <!-- 新建任务 -->
            <add-task-modal ref="addTaskModal" @callBack="addTaskCallBack"></add-task-modal>
            <!-- 客户详情 抽屉 -->
            <drawerCrm :drawerVisible.sync="drawerVisible" :routeUrl="routeUrl" :title="drawerTitle" :dataItem="dataItem"></drawerCrm>

        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import moment from "moment";
import { mapState } from "vuex";
import { Controlwidth } from "@/utils/antTableComponents";
import { PageList, Save as SaveLinkMan, disable, enable, detail, historyList , setKP} from "@/api/crm/linkMan";
import { clearValue, clearKeys } from "@/utils/tool/object";
import { initValidator, checkAll } from "@/utils/validator/validator";
import { pageForSelect } from "@/api/crm/customer";
import { pageList as taskPage } from "@/api/crm/call/callTask";
import { addCallTaskDetail } from "@/api/crm/call/callTaskDetail";

import dynamicList from "@/mixins/dynamicList";
import MiddleUtils from '@/utils/middle-utils'


let searchTimeout;
export default {
    mixins: [dynamicList],
    data () {
          //任务列表
        const taskColumns = [
            //工序信息table
            {
                align: "left",
                title: "任务名称",
                dataIndex: "taskName",
                width: 150,
                scopedSlots: {
                    filterDropdown: 'taskNameFilterDropdown',
                },
            },
             {
                align: "center",
                title: "任务开始时间",
                dataIndex: "startTime",
                width: 80,
            },
             {
                align: "center",
                title: "任务结束时间",
                dataIndex: "endTime",
                width: 80,
            },
            {
                align: "left",
                title: "快呼方式",
                dataIndex: "callType",
                width: 100,
                 customRender: (text, row, index) => {
                    const type = ["人工", "去电放音"];
                    return type[text - 1];
                },
                scopedSlots: {
                    filterDropdown: 'callTypeFilterDropdown',
                },
            },
            {
                align: "center",
                title: "联系类型",
                dataIndex: "taskType",
                width: 60,
                customRender: (text, row, index) => {
                    const type = ["销售联系", "客户关怀","售后回访","投诉回访","服务支持","维修维护","客户投诉"];
                    return type[text - 1];
                },
                scopedSlots: {
                    filterDropdown: 'taskTypeFilterDropdown',
                },
            },
            {
                align: "center",
                title: "任务条数",
                dataIndex: "mobileCount",
                width: 50,
            },
            {
                align: "center",
                title: "执行数量",
                dataIndex: "dialedCount",
                width: 50,
            },
            {
                align: "center",
                title: "任务执行率",
                dataIndex: "taskType",
                width: 50,
                customRender: (text, row, index) => {
                    if(!row.dialedCount)return '--';
                    let callRate = ((row.dialedCount / row.mobileCount)*100).toFixed(2);
                    return callRate+"%";
                }
            },
            {
                align: "center",
                title: "业务状态",
                dataIndex: "businessStatus",
                width: 60,
                customRender: (text, row, index) => {
                    const resultTex = !text ? <sapn style="color: green">正常</sapn>: <sapn style="color: red">关闭</sapn> ;
                    return resultTex;
                }
            },
            {
                align: "center",
                title: "创建时间",
                dataIndex: "createDate",
                width: 80,
            },
        ];
        return {
            radioStyle: {
                display: 'block',
                height: '30px',
                lineHeight: '30px',
            },
            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------

            //gw 2021年8月16日11:04:08
            visibleSearchPlan: false,
            //gw 2021年8月16日11:04:16

            searchType: 3,       //
            source: "linkMan",
            crmType: '1,2',
            FixedConditionKeys: ["name", "crmName"],  //固定的搜索条件的Key
            customRenderCode: ["crmName", "name", "isMain", "mobile"], //table 使用插槽的列

            //下拉搜索 客户条件
            selectPostData: {
                page: {
                    current: 1,
                    size: 1000
                },
                keyWord: '',
            },
            customerSelect: [],              //下拉搜索 客户
            route: this.$route.path,

            drawerVisible: false,//客户详情抽屉
            routeUrl: '',
            drawerTitle: '',
            dataItem: [],
            crmNameValue: null,
            rowClassName: (record, index) => {
                if (record.clickActive) {
                    return 'click-table-active'
                }
            },
             //选择任务
            taskPagination: {
                defaultPageSize: 20,
                size: "small",
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.taskPagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changeTaskPageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    console.log("选择任务",page,pageSize);
                    // this.postData.current = page;
                    this.taskPagination.current = page;
                    this.taskPagination.pageSize = pageSize;
                    Object.assign(this.taskPostData, {
                        page:{
                            size: pageSize,
                            current: page,
                        }
                    });
                    this.taskPage();
                },
                showQuickJumper: true,
                showLessItems: true
            },
            taskModalVisible: false,
            taskSearchKeyWord: "",
            taskData:[],
            taskIsLoadingSearching: false,
            taskColumns,
            taskCustomClick: (record, index) => ({
                on: {
                    click: (event) => {
                        event.preventDefault();
                        //添加到 外呼任务
                        this.addCallTaskDetail(record);
                    },
                },
            }),
            // taskSelectedKeys:[],
            // taskSelectedData:[],
            taskPostData:{
                businessStatus:  0,
                page:{
                    "current": 1,
                    "size": 20
                },
            },
            //新建任务
            editModal: false,
            editItem: {
                startTimeMoment: moment(),
            }, //新增/编辑对象
            voiceMap:new Map(),     //音频Map 存储
            dateFormat: "YYYY-MM-DD HH:mm", //任务时间格式
            voice_pay: false,       // 语音播放
            isAddTask: false,       //是否已经加入 外呼任务
        };
    },
    components: {
        drawerCrm: () => import('@/components/Crm/drawer'),
        addTaskModal: () => import('@//views/crm/call/addTaskModal'),
    },
    beforeCreate: function () {
        // this.$options.components.drawerCrm = require('@/components/Crm/drawer').default
    },
    created () {
        const { formRules } = this;
        formRules["formPostData.crmId"] = { test: "required" };
    },
    watch: {
        "customerId": function (n, o) {
            console.log("watch_linkMan_customerId:", n, o);
            const { basePostData } = this;
            basePostData.customerIds = n;
            this.reset();
            this.selectedKeys = [];
            this.selectedRows = [];
        },
        $route: {
            handler (nv, ov) {
                //离开路由关闭 右侧详情抽屉
                this.drawerVisible = false;
            },
            deep: true
        },
    },
    activated () {
    },
    mounted () {
        
        MiddleUtils.$on('syncList', (value) => {
            if(this.$route.path == '/crm/linkMan/list'){
                console.log("刷新syncList---联系人");
                this.PageList();    
            }
        })
    },
    updated () {
        Controlwidth("linkMan_tb", 50);
    },
    computed: {
        //是否显示 新增按钮
        addBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                customerId
                && (permissions.includes("crm:linkMan:add")
                    || (crmType == 0 && permissions.includes("crm:clue:linkMan:add"))
                    || (crmType == 1 && permissions.includes("crm:potential:linkMan:add"))
                    || (crmType == 2 && permissions.includes("crm:deals:linkMan:add"))
                )
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 编辑按钮
        editBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:linkMan:edit")
                || (crmType == 0 && permissions.includes("crm:clue:linkMan:edit"))
                || (crmType == 1 && permissions.includes("crm:potential:linkMan:edit"))
                || (crmType == 2 && permissions.includes("crm:deals:linkMan:edit"))
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 删除按钮
        disableBtnShow: function () {
            const { customerId, customer, permissions, userInfo } = this;
            const { crmType } = customer;
            let isShow = false;
            if (
                permissions.includes("crm:linkMan:disable")
                || (crmType == 0 && permissions.includes("crm:clue:linkMan:disable"))
                || (crmType == 1 && permissions.includes("crm:potential:linkMan:disable"))
                || (crmType == 2 && permissions.includes("crm:deals:linkMan:disable"))
            ) {
                isShow = true;
            }
            return isShow;
        },
        //是否显示 加入外呼任务 按钮
        addTaskBtnShow: function () {
            const { permissions } = this;
            let isShow = false;
            if (
                permissions.includes("outbound:list")
            ) {
                isShow = true;
            }
            return isShow;
        },
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    methods: {
        moment,
        OpenCallingBox(linkMan){
            let {userInfo} = this;
            console.log("userInfo----------->>>",userInfo);
            let { companyId,companyName } = userInfo;
            let { id,name,crmId,crmName,mobile} = linkMan;
            let callParams = {
                companyId,
                companyName,
                linkManId: id,
                linkManName: name, 
                crmId,crmName,
                mobile,
                createUserId: userInfo.id,
                createUserName: userInfo.name
            }
            console.log("联系人直接拨打号码传参数----------->>>",callParams);
            MiddleUtils.$emit("OpenCallingBox",callParams);
        },
        inputLog (e) {
            console.log("from_select input:", e, JSON.stringify(this.formPostData))
        },
        taskNameConditionChange(e){
            console.log("联系人页面_外呼任务名称变化，e.target.value",e.target.value,this.taskPostData.taskName);
        },
        //延迟 搜索
        delaySearch (value) {
            console.log("delaySearch...", value, searchTimeout);
            if (searchTimeout) {
                clearTimeout(searchTimeout);
                searchTimeout = null;
            }
            const go = () => { this.pageForSelect(value) }
            searchTimeout = setTimeout(go, 400);
        },
        //下拉搜索 客户
        pageForSelect (keyWord) {
            const { selectPostData } = this;
            Object.assign(selectPostData, { keyWord });
            selectPostData.crmTypes = [1, 2];//潜在客户
            pageForSelect(selectPostData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records } = data;
                    this.customerSelect = records;
                    console.log("搜索结果", records)
                }
            }).catch(error => { });
        },
        //跳转到 客户详情
        goToDetail (item, tabkey) {
            const { permissions } = this;
            if (!this.customerId && (permissions.includes("crm:potential:edit") || permissions.includes("crm:potential:edit") || permissions.includes("crm:deals:edit"))) {
                // this.$router.push(`/crm/customer/detail/${item.crmName}/${item.crmId}/${tabkey}`);
                this.drawerVisible = true;
                this.routeUrl = window.location.host + `/crm/customer/detail/${item.crmName}/${item.crmId}/${tabkey}`;
                this.drawerTitle = item.crmName;
                this.dataItem = item;
                this.$forceUpdate();
                //给点击的行一个颜色
                this.data.map(d => {
                    this.$set(d, 'clickActive', false)
                });
                this.$set(item, 'clickActive', true)
            }
        },
        //添加
        AddItem () {
            this.selectPostData.keyWord = '';
            this.pageForSelect();
            const { formErrors, customer } = this;
            const { crmName, id } = customer;
            let formPostData = {
                crmName,
                crmId: id
            }
            Object.assign(this, { formPostData })
            clearKeys(formErrors);
            this.isFromShow = true;
            this.ModalVisible = true;

            console.log("AddItem_formErrors->", formErrors)
        },
        //编辑
        EditItem (id) {
            const { selectedKeys, editBtnShow } = this;
            if (!editBtnShow) {
                return false;
            }
            if (!id) {
                let isOk = this.checkSingleSelectKey();
                if (!isOk) {
                    return false;
                }
                id = selectedKeys[0];
            }
            this.selectPostData.keyWord = '';
            this.pageForSelect();
            //查询联系人
            detail({ id }).then(response => {
                console.log("获取联系人详情", response);
                if (response.code === 200) {
                    const { data } = response;
                    // delete data.createDate;
                    // delete data.updateDate;
                    delete data.status;
                    Object.assign(this, {
                        formPostData: data,
                    });
                    this.initCustomize();
                }
            })
                .catch(error => { });
            this.isFromShow = true;
            this.ModalVisible = true;
        },
        onSerch () {
            const { postData } = this;
            postData.page.current = 1;
            this.PageList();
            this.cancel();
        },
        // 获取列表
        PageList (flag) {
            const { postData, onOffDefineFields, customerId, customer, source } = this;
            // Object.assign(postData,{ customerIds: this.customerId})
            console.log("潜在客户——搜索条件：", onOffDefineFields, customerId, customer);
            postData.dtos = onOffDefineFields;
            postData.type = source;   //查询共享模块
            if (customerId) {
                postData.crmType = customer.crmType;

            }
            this.loading = true;
            this.selectedKeys = [];
            this.selectedRows = [];
            if (flag == 'history') {
                this.isHistoryFlag = true;
                let bbb = false;
                this.columns.forEach(item => {
                    if (item.dataIndex == 'type') {
                        bbb = true;
                    }
                });
                if (!bbb) {
                    this.columns.unshift({
                        align: "center",
                        dataIndex: "operateDate",
                        key: "operateDate",
                        onLocked: false,
                        sorter: false,
                        title: "操作时间",
                        width: 140,
                    })
                    this.columns.unshift({
                        align: "center",
                        dataIndex: 'type',
                        key: "type",
                        title: '类型',
                        onLocked: false,
                        sorter: false,
                        width: 50,
                        customRender: (text) => {
                            return text == 1 ? '删除' : '修改';
                        }
                    })
                    this.columns.unshift({
                        align: "left",
                        dataIndex: "operateUserName",
                        key: "operateUserName",
                        onLocked: false,
                        sorter: false,
                        title: "操作人",
                        width: 70,
                    })
                }
                let data = {
                    crmId: this.customerId
                }
                historyList(data).then(response => {
                    this.loading = false;
                    console.log("获取潜在客户列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        //转换自定义数据数据
                        this.defineFieldsAddToData(records);
                        this.data = records;
                        console.log("转换后的数据：records", records);
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                }).catch(error => { });
            } else {
                this.isHistoryFlag = false;
                this.columns.forEach((item, index) => {
                    if (item.dataIndex == 'operateUserName') {
                        this.columns.splice(index, 1)
                    } else if (item.dataIndex == 'operateDate') {
                        this.columns.splice(index, 1)
                    }
                });
                this.columns = this.columns.filter((res) => { return res.dataIndex != 'type' });
                PageList(postData).then(response => {
                    this.loading = false;
                    console.log("获取潜在客户列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        //转换自定义数据数据
                        this.defineFieldsAddToData(records);

                        this.data = records;
                        console.log("转换后的数据：records", records);
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                }).catch(error => { });
            }
        },
        //提交表单
        onSubmit () {
            const {
                crmType,
                formRules,
                formPostData,
                formErrors,
                onOffDefineFields,
                customerId
            } = this;
            //全部校验一次
            checkAll(this, formRules, formPostData, formErrors);
            if (Object.keys(formErrors).length > 0) {
                this.isFromShow = false;
                this.$nextTick(function () {
                    this.isFromShow = true;
                });
                return false;
            }
            //自定义字段 重组
            let defineFieldsSets = onOffDefineFields.filter(f => f.dataType == 2);
            let defineFields = {};
            //获取重组后的自定义集合
            this.getDefineFields(defineFields, formPostData, defineFieldsSets);
            Object.assign(formPostData, {
                defineFields: JSON.stringify(defineFields)
            });
            let _this = this;
            SaveLinkMan(formPostData)
                .then(response => {
                    console.log("SaveCustomer_response.code", response.code);
                    if (response.code === 200) {
                        _this.$message.success("保存成功");
                        _this.hideModal();
                        if (_this.customerId) {
                            MiddleUtils.$emit('syncList')
                        }
                        _this.PageList();
                    }
                })
        },
        //从 现有客户中  添加 联系人 到任务明细
        addCallTaskDetail(taskItem){
            const { selectedRows } = this;
            let _this = this;
            if(selectedRows.length == 0)this.$message.warning("请选择联系人");
              this.$confirm({
                title: '确认',
                content: <span>您确定要添加到{<span style='color:red;'>{taskItem.taskName}</span>}外呼任务吗？</span>,
                onOk () {
                    let crmCallTaskDetailList =  _.cloneDeep(selectedRows)
                    crmCallTaskDetailList.forEach(item=>{
                        item.linkManId = item.id;
                        item.linkManName = item.name;
                        delete item.id;
                    });

                    let postData = {
                        taskId: taskItem.id,
                        crmCallTaskDetailList
                    }
                    addCallTaskDetail(postData).then(response=>{
                        if (response.code === 200) {
                            _this.$message.success("添加成功")
                            _this.taskModalVisible = false;
                            _this.PageList();
                        }
                    });
                },
                onCancel () { },
            });

            

        },
        
        //删除联系人
        Disable () {
            const { selectedKeys } = this;
            let isOk = this.checkSingleSelectKey(true);
            if (!isOk) {
                return false;
            }
            let _this = this;
            let ids = selectedKeys.join(",");
            this.$confirm({
                title: '确认',
                content: '您确定要删除该联系人吗？',
                onOk () {
                    disable({ ids })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("删除成功");
                                _this.selectedKeys = [];
                                _this.selectedRows = [];
                                _this.PageList();
                            }
                        })
                },
                onCancel () { },
            });
        },
        //设置关键人
        setKP () {
            const { selectedKeys,customerId } = this;
            let isOk = this.checkSingleSelectKey(true);
            if (!isOk) {
                return false;
            }
            let _this = this;
            let linkManId = selectedKeys[0];
            this.$confirm({
                title: '确认',
                content: '您确定要设置该联系人为关键人吗？',
                onOk () {
                    setKP({ linkManId,crmId:customerId })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("设置成功");
                                _this.selectedKeys = [];
                                _this.PageList();
                            }
                        })
                },
                onCancel () { },
            });
        },
        
        //gw 2021年8月16日11:51:51
        cancel () {
            //置空临时查询条件
            // if (this.planActive == 0) {
            //     setTimeout(() => {
            //         this.onOffDefineFields.forEach(item => {
            //             item.value = '';
            //         });
            //     }, 200)
            // }
            this.visibleSearchPlan = false;
        },
        onShowSerch () {
            this.visibleSearchPlan = true;
        },

        /************ 任务 ************/
        onTaskShow(){
            const { selectedRows } = this;
            if(selectedRows.length == 0){
                this.$message.warn("请选择记录");
                return;
            }
            let warnMessage = "";
            selectedRows.forEach(f=>{
                if(f.crmTaskId && f.linkManCrmTaskId){
                    if(warnMessage)warnMessage +="；";
                    warnMessage += f.name + ",已经加入到外呼任务中";
                }
            });
            if(warnMessage){
                this.$message.warn(warnMessage);
                return;
            }
            this.taskModalVisible = true;
            this.isAddTask = selectedRows[0].crmTaskId > 0;
            this.taskPage(selectedRows[0].crmTaskId);
        },
        onTaskClose(){
            this.taskModalVisible = false;
            this.isAddTask = false;
        },
        //获取任务列表
        taskPage (taskId) {
            const { taskPostData } = this;
            if(taskId){
                taskPostData.taskId = taskId;
            }
            taskPage(taskPostData).then(response => {
                console.log("获取外呼任务列表", response);
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.taskData = records;
                    this.data.forEach(item => {
                        item.key = item.id;
                    });
                    Object.assign(this.taskPagination, {
                        total
                    });
                }
            }).catch(error => { });
        },
        changeTaskPageSize (e) {
            const value = e.target.value;
            Object.assign(this.taskPostData, {
                page:{
                    size: value,
                    current: 1,
                }
            });
            Object.assign(this.taskPagination, {
                pageSize: Number.parseInt(value),
                current: 1,
            });
            // this.pageList();
        },
        /************ 新增任务 ************/
        addTask() {
            let editItem = {
                startTimeMoment: moment(),
                taskName:null,
                callType:1,
                intervalTime:15,
                sdCallTimes:3,
                voiceid:null,
                voiceUrl:null
            };
            this.$refs.addTaskModal.openTaskModal(editItem);
        },
        addTaskCallBack(){
            this.taskPage();
        }
    },
};
</script>

